﻿using System;
using System.Collections.Generic;
using System.Linq;
using NHibernate.Mapping.ByCode;
using Xenta.Enums;
using Xenta.Utils;

namespace Xenta.Entities
{
    /// <summary>
    /// Represents the supplier entity.
    /// </summary>
    /// <remarks><pre>
    /// The entity regarding the disclosure level.
    /// 
    /// + Entire
    ///    | - Managers(of the Extended level)
    ///    | - Tags(of the Extended level)
    ///    | - Categories(of the Extended level)
    ///    | - Attributes(of the Extended level)
    ///    | - Addresses(of the Extended level)
    ///  + Extended
    ///   + Base
    ///    | - FileGroup(of the Primary level)
    ///    | - CommentCount
    ///    | - RatingCount
    ///    | - RatingAverage
    ///    | - ItemCount
    ///    | - Flags
    ///    | - UpdatedOn
    ///    | - CreatedOn
    ///    | - Translations(of the same level)
    ///    + Keys
    ///     + Primary
    ///      | - EntityID
    /// 
    /// Note: upper level includes lower level.
    /// </pre></remarks>
    public class CatalogSupplierEntity : AuditableEntity,
        IRelationHolder<CatalogCategoryEntity>,
        IRelationHolder<LookupAttributeEntity>,
        IRelationHolder<CatalogTagEntity>,
        IRelationHolder<CatalogManagerEntity>
    {
        #region Fields

        private FileGroupEntity _fileGroup;
        private ICollection<CatalogManagerEntity> _managers;
        private ICollection<CatalogSupplierAddressEntity> _addresses;
        private ICollection<CatalogCategoryEntity> _categories;
        private ICollection<LookupAttributeEntity> _attributes;
        private ICollection<CatalogTagEntity> _tags;
        private ICollection<CatalogItemEntity> _items;
        private ICollection<CatalogItemGroupEntity> _groups;
        private ICollection<TCatalogSupplierEntity> _translations;
        private ICollection<CatalogSupplierCommentEntity> _comments;
        private ICollection<CatalogSupplierRatingEntity> _ratings;

        #endregion

        #region Ctors

        /// <summary>
        /// Initializes a new class instance.
        /// </summary>
        public CatalogSupplierEntity()
        {
            _fileGroup = null;
            _managers = new List<CatalogManagerEntity>();
            _addresses = new List<CatalogSupplierAddressEntity>();
            _categories = new List<CatalogCategoryEntity>();
            _attributes = new List<LookupAttributeEntity>();
            _tags = new List<CatalogTagEntity>();
            _items = new List<CatalogItemEntity>();
            _groups = new List<CatalogItemGroupEntity>();
            _translations = new List<TCatalogSupplierEntity>();
            _comments = new List<CatalogSupplierCommentEntity>();
            _ratings = new List<CatalogSupplierRatingEntity>();
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets or sets the file group identifier.
        /// </summary>
        public virtual int FileGroupID
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the file group.
        /// </summary>
        public virtual FileGroupEntity FileGroup
        {
            get
            {
                return FileGroupID == 0 ? null : _fileGroup;
            }
            set
            {
                _fileGroup = value;
                FileGroupID = value == null ? 0 : value.EntityID;
            }
        }

        /// <summary>
        /// Gets or sets the numer of comments.
        /// </summary>
        public virtual int CommentCount
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the numer of ratings.
        /// </summary>
        public virtual int RatingCount
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the average rating.
        /// </summary>
        public virtual byte RatingAverage
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the number of items.
        /// </summary>
        public virtual int ItemCount
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the flags.
        /// </summary>
        public virtual CatalogSupplierFlags Flags
        {
            get;
            set;
        }

        #endregion

        #region Collections
        
        /// <summary>
        /// Gets or sets the manager collection.
        /// </summary>
        public virtual ICollection<CatalogManagerEntity> Managers
        {
            get
            {
                return _managers;
            }
            set
            {
                _managers = value;
            }
        }

        /// <summary>
        /// Gets or sets the address collection.
        /// </summary>
        public virtual ICollection<CatalogSupplierAddressEntity> Addresses
        {
            get
            {
                return _addresses;
            }
            set
            {
                _addresses = value;
            }
        }

        /// <summary>
        /// Gets or sets the category collection.
        /// </summary>
        public virtual ICollection<CatalogCategoryEntity> Categories
        {
            get
            {
                return _categories;
            }
            set
            {
                _categories = value;
            }
        }

        /// <summary>
        /// Gets or sets the attribute collection.
        /// </summary>
        public virtual ICollection<LookupAttributeEntity> Attributes
        {
            get
            {
                return _attributes;
            }
            set
            {
                _attributes = value;
            }
        }

        /// <summary>
        /// Gets or sets the tag collection.
        /// </summary>
        public virtual ICollection<CatalogTagEntity> Tags
        {
            get
            {
                return _tags;
            }
            set
            {
                _tags = value;
            }
        }

        /// <summary>
        /// Gets or sets the related item collection.
        /// </summary>
        public virtual ICollection<CatalogItemEntity> Items
        {
            get
            {
                return _items;
            }
            set
            {
                _items = value;
            }
        }

        /// <summary>
        /// Gets or sets the group collection.
        /// </summary>
        public virtual ICollection<CatalogItemGroupEntity> Groups
        {
            get
            {
                return _groups;
            }
            set
            {
                _groups = value;
            }
        }

        /// <summary>
        /// Gets or sets the supplier translations.
        /// </summary>
        public virtual ICollection<TCatalogSupplierEntity> Translations
        {
            get
            {
                return _translations;
            }
            set
            {
                _translations = value;
            }
        }

        /// <summary>
        /// Gets the ratings.
        /// </summary>
        public virtual ICollection<CatalogSupplierCommentEntity> Comments
        {
            get
            {
                return _comments;
            }
            set
            {
                _comments = value;
            }
        }

        /// <summary>
        /// Gets the ratings.
        /// </summary>
        public virtual ICollection<CatalogSupplierRatingEntity> Ratings
        {
            get
            {
                return _ratings;
            }
            set
            {
                _ratings = value;
            }
        }

        #endregion

        #region Methods

        /// <summary>
        /// Gets the supplier translation.
        /// </summary>
        /// <param name="languageID">The language identifier.</param>
        /// <returns>The supplier translation.</returns>
        public virtual TCatalogSupplierEntity Translation(int languageID)
        {
            return _translations.SingleOrDefault(x => x.Language.EntityID == languageID);
        }

        /// <summary>
        /// Maps a category to the supplier.
        /// </summary>
        /// <param name="child">The category to map.</param>
        public virtual void Map(CatalogCategoryEntity child)
        {
            if(Categories.Contains(child))
                return;
            Categories.Add(child);
        }

        /// <summary>
        /// Unmaps the category from the supplier.
        /// </summary>
        /// <param name="child">The category to unmap.</param>
        public virtual void Unmap(CatalogCategoryEntity child)
        {
            if(!Categories.Contains(child))
                return;
            Categories.Remove(child);
        }

        /// <summary>
        /// Maps an attribute to the supplier.
        /// </summary>
        /// <param name="child">The attribute to map.</param>
        public virtual void Map(LookupAttributeEntity child)
        {
            if(Attributes.Contains(child))
                return;
            Attributes.Add(child);
        }

        /// <summary>
        /// Unmaps the attribute from the supplier.
        /// </summary>
        /// <param name="child">The attribute to unmap.</param>
        public virtual void Unmap(LookupAttributeEntity child)
        {
            if(!Attributes.Contains(child))
                return;
            Attributes.Remove(child);
        }

        /// <summary>
        /// Maps a tag to the supplier.
        /// </summary>
        /// <param name="child">The tag to map.</param>
        public virtual void Map(CatalogTagEntity child)
        {
            if(Tags.Contains(child))
                return;
            Tags.Add(child);
        }

        /// <summary>
        /// Unmaps the tag from the supplier.
        /// </summary>
        /// <param name="child">The tag to unmap.</param>
        public virtual void Unmap(CatalogTagEntity child)
        {
            if(!Tags.Contains(child))
                return;
            Tags.Remove(child);
        }

        /// <summary>
        /// Maps a manager to the supplier.
        /// </summary>
        /// <param name="child">The manager to map.</param>
        public virtual void Map(CatalogManagerEntity child)
        {
            if(Managers.Contains(child))
                return;
            Managers.Add(child);
        }

        /// <summary>
        /// Unmaps the manager from the supplier.
        /// </summary>
        /// <param name="child">The manager to unmap.</param>
        public virtual void Unmap(CatalogManagerEntity child)
        {
            if(!Managers.Contains(child))
                return;
            Managers.Remove(child);
        }

        #endregion

        #region Utilities

        protected override void Disclose(IDictionary<String, Object> obj,
            DisclosureLevel level,
            IDictionary<String, String> options)
        {
            base.Disclose(obj, level, options);
            if(level >= DisclosureLevel.Base)
            {
                obj["FileGroup"] = FileGroup != null
                    ? FileGroup.Disclose(DisclosureLevel.Primary, options)
                    : null;
                obj["CommentCount"] = CommentCount;
                obj["RatingCount"] = RatingCount;
                obj["RatingAverage"] = RatingAverage;
                obj["ItemCount"] = ItemCount;
                obj["Flags"] = Flags.ToString();
                obj["Translations"] = (options.ContainsKey("TranslatedTo")
                    ? Translations.Where(x => options["TranslatedTo"].Contains(x.Language.Code))
                    : Translations)
                    .Map(x => x.Disclose(level, options));
            }
            if(level >= DisclosureLevel.Entire)
            {
                obj["Managers"] = Managers.Map(x => x.Disclose(DisclosureLevel.Extended, options));
                obj["Tags"] = Tags.Map(x => x.Disclose(DisclosureLevel.Extended, options));
                obj["Categories"] = Categories.Map(x => x.Disclose(DisclosureLevel.Extended, options));
                obj["Attributes"] = Attributes.Map(x => x.Disclose(DisclosureLevel.Extended, options));
                obj["Addresses"] = Addresses.Map(x => x.Disclose(DisclosureLevel.Extended, options));
            }
        }

        #endregion
    }

    /// <summary>
    /// The entity NHibernate mapping.
    /// </summary>
    public class CatalogSupplierMapping : EntityMapping<CatalogSupplierEntity>
    {
        /// <summary>
        /// Initializes a new class instance.
        /// </summary>
        public CatalogSupplierMapping()
        {
            Table("fwk_CatalogSuppliers");
            Id(x => x.EntityID, m =>
            {
                m.Column("SupplierID");
                m.Generator(Generators.Identity);
            });
            Property(x => x.FileGroupID, m =>
            {
                m.Column("FileGroupID");
                m.NotNullable(true);
            });
            ManyToOne(x => x.FileGroup, m =>
            {
                m.Column("FileGroupID");
                m.NotFound(NotFoundMode.Ignore);
                m.Insert(false);
                m.Update(false);
            });
            Property(x => x.ItemCount, m =>
            {
                m.NotNullable(true);
            });
            Property(x => x.CommentCount, m =>
            {
                m.NotNullable(true);
            });
            Property(x => x.RatingCount, m =>
            {
                m.NotNullable(true);
            });
            Property(x => x.RatingAverage, m =>
            {
                m.NotNullable(true);
            });
            Property(x => x.Flags, m =>
            {
                m.NotNullable(true);
            });
            Property(x => x.CreatedOn, m =>
            {
                m.NotNullable(true);
            });
            Property(x => x.UpdatedOn, m =>
            {
                m.NotNullable(true);
            });
            Bag(x => x.Attributes, m =>
            {
                m.Table("fwk_MCatalogSupplierAttributes");
                m.Key(k =>
                {
                    k.Column("SupplierID");
                    k.ForeignKey("FK_fwk_MCatalogSupplierAttributes_fwk_CatalogSuppliers");
                    k.NotNullable(true);
                });
            },
            a =>
            {
                a.ManyToMany(m =>
                {
                    m.Column("AttributeID");
                    m.ForeignKey("FK_fwk_MCatalogSupplierAttributes_fwk_LookupAttributes");
                });
            });
            Bag(x => x.Categories, m =>
            {
                m.Table("fwk_MCatalogSupplierCategories");
                m.Key(k =>
                {
                    k.Column("SupplierID");
                    k.ForeignKey("FK_fwk_MCatalogSupplierCategories_fwk_CatalogSuppliers");
                    k.NotNullable(true);
                });
            },
            a =>
            {
                a.ManyToMany(m =>
                {
                    m.Column("CategoryID");
                    m.ForeignKey("FK_fwk_MCatalogSupplierCategories_fwk_CatalogCategories");
                });
            });
            Bag(x => x.Tags, m =>
            {
                m.Table("fwk_MCatalogSupplierTags");
                m.Key(k =>
                {
                    k.Column("SupplierID");
                    k.ForeignKey("FK_fwk_MCatalogSupplierTags_fwk_CatalogSuppliers");
                    k.NotNullable(true);
                });
            },
            a =>
            {
                a.ManyToMany(m =>
                {
                    m.Column("TagID");
                    m.ForeignKey("FK_fwk_MCatalogSupplierTags_fwk_CatalogTags");
                });
            });
            Bag(x => x.Groups, m =>
            {
                m.Table("fwk_CatalogItemGroups");
                m.Key(k =>
                {
                    k.Column("SupplierID");
                    k.ForeignKey("FK_fwk_CatalogItemGroups_fwk_CatalogSuppliers");
                    k.NotNullable(true);
                });
                m.Inverse(true);
            },
            a =>
            {
                a.OneToMany();
            });
            Bag(x => x.Items, m =>
            {
                m.Table("fwk_CatalogItems");
                m.Key(k =>
                {
                    k.Column("SupplierID");
                    k.ForeignKey("FK_fwk_CatalogItems_fwk_CatalogSuppliers");
                    k.NotNullable(true);
                });
                m.Inverse(true);
            },
            a =>
            {
                a.OneToMany();
            });
            Bag(x => x.Addresses, m =>
            {
                m.Table("fwk_Addresses");
                m.Key(k =>
                {
                    k.Column("HolderID");
                    k.NotNullable(true);
                });
                m.Inverse(true);
            },
            a =>
            {
                a.OneToMany();
            });
            Bag(x => x.Managers, m =>
            {
                m.Table("fwk_MCatalogSupplierManagers");
                m.Key(k =>
                {
                    k.Column("SupplierID");
                    k.ForeignKey("FK_fwk_MCatalogSupplierManagers_fwk_CatalogSuppliers");
                    k.NotNullable(true);
                });
            },
            a =>
            {
                a.ManyToMany(m =>
                {
                    m.Column("ManagerID");
                    m.ForeignKey("FK_fwk_MCatalogSupplierManagers_fwk_CatalogManagers");
                });
            });
            Bag(x => x.Translations, m =>
            {
                m.Table("fwk_TCatalogSuppliers");
                m.Key(k =>
                {
                    k.Column("SupplierID");
                    k.ForeignKey("FK_fwk_TCatalogSuppliers_fwk_CatalogSuppliers");
                    k.NotNullable(true);
                });
                m.Inverse(true);
                m.BatchSize(10);
            },
            a =>
            {
                a.OneToMany();
            });
            Bag(x => x.Comments, m =>
            {
                m.Table("fwk_Comments");
                m.Key(k =>
                {
                    k.Column("HolderID");
                    k.NotNullable(true);
                });
                m.Inverse(true);
            },
            a =>
            {
                a.OneToMany();
            });
            Bag(x => x.Ratings, m =>
            {
                m.Table("fwk_Ratings");
                m.Key(k =>
                {
                    k.Column("HolderID");
                    k.NotNullable(true);
                });
                m.Inverse(true);
            },
            a =>
            {
                a.OneToMany();
            });
        }
    }
}
